package com.open4cn.simulator.protocol.xrite;

import com.open4cn.simulator.core.ext.OutMessage;
import com.open4cn.simulator.core.util.TranscodeUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

/**
 * @author yinxiaopeng
 * @version 1.0.0
 * @company 致景科技
 * @department 飞梭BU/研发
 * @description
 * @Email yinxiaopeng@zj.tech
 * @date 2022-05-13 00:44
 */
public class Xrite7800Eecoder extends MessageToByteEncoder<OutMessage> {

    @Override
    protected void encode(ChannelHandlerContext ctx, OutMessage msg, ByteBuf out) throws Exception {
        StringBuilder builder = new StringBuilder();
        builder.append(TranscodeUtil.hexToString("7e"))
                .append(TranscodeUtil.hexToString("00"))
                .append(TranscodeUtil.hexToString("00"))
                .append(getBodyLength(msg.get().length()))
                .append(msg.get())
                .append(TranscodeUtil.hexToString("7f"));
        out.writeBytes(builder.toString().getBytes());
    }

    /**
     * 计算返回内容长度
     *
     * @param length
     * @return
     */
    private String getBodyLength(int length) {
        String high = TranscodeUtil.hexToString(TranscodeUtil.numTohexString(length / 256));
        String low = TranscodeUtil.hexToString(TranscodeUtil.numTohexString(length % 256));
        return high + low;
    }
}
